# -*- coding: utf - 8 - *-
from openpyxl import load_workbook
import datetime
import json
import requests  # 先导入爬虫的库，不然调用不了爬虫的函数
from TrayIcon import TrayIcon
from win_2048 import Ui_MainWindow
from DB_OPERTER import DB
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QTableWidgetItem
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from lxml import etree
from qdarkstyle import load_stylesheet
import sys
import threads


def make_html_contents(text, flag="b"):
    # html = etree.HTML(text["div"]["p"])
    html = etree.HTML(text)

    html_ = html.xpath('//text()')
    if html_.__len__() <= 1:
        name = ""
    elif html_.__len__() >= 2:
        name = html_[1]

    html_data = html.xpath('//div//text()')
    data = ""
    for s in html_data:
        data += "\n****" + s
    # print("name, data", name, data)
    return name, data


class MED_SELL(QMainWindow, Ui_MainWindow):
    _signal = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        # self.setWindowFlags(Qt.FramelessWindowHint)
        self.retranslateUi(self)
        self.Table_Init()
        self.label_5.setText("行业查询工具3.2")
        self.label_4.setText("键入单位全名 或 主要营业范围 查询 不超过28个字\n企业建议使用主要营业范围查询\n同时注意在企查查中核对信息")
        self.Connections()
        self.DB = DB()
        # self.GETTER = GET_2048_INFO()
        self.type_ = ""
        self.List_Refresh()

        # self.bn_update_url_stop.setEnabled(False)
        # self.bn_update_info_stop.setEnabled(False)
        self.headers = {

            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            'Host': "jcfx.tjj.zj.gov.cn:6443",
            "Referer": "https://jcfx.tjj.zj.gov.cn:6443/autocode-project/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "sec-ch-ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "Windows"
        }
        self.tree_headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Cookie": "acw_tc=2760778217059808673181768e178bae67d4e0ab6f4c78ee3b7754c6e0677c; Hm_lvt_1dfb854979136f79bcf4ca4bd708faa6=1705909491,1705910462,1705980868; Hm_lpvt_1dfb854979136f79bcf4ca4bd708faa6=1705980913",

            'Host': "tjcx.scimall.org",
            "Referer": "https://jcfx.tjj.zj.gov.cn:6443/autocode-project/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "sec-ch-ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "Windows"
        }

        self.index_url = 0

        self.count = 1
        self.tray = TrayIcon(self)
        self.tray.show()
        file = open("./init/log.txt", 'w').close()
        # url = "http://tjcx.scimall.org/js/data.json"
        # response = self.request_source(url, self.tree_headers)
        # print("response.text", response.text)
        # self.tree_data = json.loads(response.text)

        with open("./init/init.json", 'r', encoding='utf-8') as file:
            self.tree_data = json.loads(file.read())
        # print(" self.tree_data", self.tree_data)
        # print("self.tree_data", self.tree_data)
        # tree = ET.parse('./init/init.xml')
        # xml_data = tree.getroot()
        # # here you can change the encoding type to be able to set it to the one you need
        # xmlstr = ET.tostring(xml_data, encoding='utf-8', method='xml')
        # self.tree_data = xmltodict.parse(xmlstr)["root"]
        # # self.tree_data = json.loads(xmlstr)
        # print("self.tree_data", self.tree_data)
        self.init_root()

        self.Move = False

    def Connections(self):

        self.tb_urls.cellDoubleClicked.connect(self.set_html)

        self.bn_search.clicked.connect(self.List_Refresh)
        self.bn_clear.clicked.connect(self.List_Clear)
        self.bn_mini.clicked.connect(self.minimized)
        self.bn_exit.clicked.connect(self.Exit)

        self.treeWidget.itemSelectionChanged.connect(self.set_contents)

        # ----------------------------SEARCHER-------------------------------------
        # ----code search----
        self.bn_code_search.clicked.connect(self.code_search)
        self.bn_code_search_goto.clicked.connect(self.code_search_goto)

        # ----name search----
        self.bn_name_search.clicked.connect(self.name_search)
        self.bn_name_search_goto.clicked.connect(self.name_search_goto)

        # ----contents search----
        self.bn_contents_search.clicked.connect(self.contents_search)
        self.bn_contents_search_goto.clicked.connect(self.contents_search_goto)

        # --------------------------------------------------------------------------
        self.bn_tree_expand_all.clicked.connect(self.expandItem)
        self.bn_tree_collapse_all.clicked.connect(self.collapseall)

        # ------------------信号---------------------
        self.cb_code_search_result.currentIndexChanged.connect(self.cb_code_indexChange)
        self.cb_name_search_result.currentIndexChanged.connect(self.cb_name_indexChange)
        self.cb_contents_search_result.currentIndexChanged.connect(self.cb_contents_indexChange)
# -----------------------------------------------------------    查询部分    --------------------------------------------------------------

# ---------------------    Code Search    ----------------------------

    def cb_code_indexChange(self):
        if self.flag_cb_code_search_result == 1:
            self.code_search_goto()

    def cb_name_indexChange(self):
        if self.flag_cb_name_search_result == 1:
            self.name_search_goto()

    def cb_contents_indexChange(self):
        if self.flag_cb_contents_search_result == 1:
            self.contents_search_goto()

    def expandItem(self):
        self.treeWidget.expandAll()      # 展开添加的节点

    def collapseall(self):
        self.treeWidget.collapseAll()      # 展开添加的节点

    def code_search(self, text):
        self.flag_cb_code_search_result = 0
        txt = self.le_code_search.text()
        if txt != None:
            # print("txt", txt)
            res = [a + "|" + b for a, b in self.DB.db_search_code(txt)]
            self.cb_code_search_result.clear()
            self.cb_code_search_result.addItems(res)
        self.flag_cb_code_search_result = 1

    def code_search_find_item(self, code):
        iterator = QtWidgets.QTreeWidgetItemIterator(self.treeWidget)
        while iterator.value():
            if iterator.value().text(0) == code:
                tree_item = iterator.value()
                break
            iterator.__iadd__(1)
        return tree_item

    def code_search_goto(self):  # 如果是combobox 变化就激活这个槽函数
        code, name = self.cb_code_search_result.currentText().split("|")
        # for i in range(1, int(treecode.__len__() / 3) + 1):
        # print("i", i)
        # print("treecode[:i]", treecode[:i * 3])
        child = self.code_search_find_item(code)
        self.treeWidget.setCurrentItem(child)
        self.treeWidget.setFocus()

# ---------------------    Code Search    ----------------------------
    def name_search(self, text):
        self.flag_cb_name_search_result = 0
        txt = self.le_name_search.text()
        if txt != None:
            # print("txt", txt)
            res = [a + "|" + b for a, b in self.DB.db_search_name(txt)]
            self.cb_name_search_result.clear()
            self.cb_name_search_result.addItems(res)
        self.flag_cb_name_search_result = 1

    def name_search_find_item(self, code):
        iterator = QtWidgets.QTreeWidgetItemIterator(self.treeWidget)
        while iterator.value():
            if iterator.value().text(0) == code:
                tree_item = iterator.value()
                break
            iterator.__iadd__(1)
        return tree_item

    def name_search_goto(self):  # 如果是combobox 变化就激活这个槽函数
        code, name = self.cb_name_search_result.currentText().split("|")
        # for i in range(1, int(treecode.__len__() / 3) + 1):
        # print("i", i)
        # print("treecode[:i]", treecode[:i * 3])
        child = self.name_search_find_item(code)
        self.treeWidget.setCurrentItem(child)
        self.treeWidget.setFocus()
# ---------------------    contents Search    ----------------------------

    def contents_search(self, text):
        self.flag_cb_contents_search_result = 0
        txt = self.le_contents_search.text()
        if txt != None:
            # print("txt", txt)
            res = [a + "|" + b for a, b in self.DB.db_search_contents(txt)]
            # print("res", res)
            self.cb_contents_search_result.clear()
            self.cb_contents_search_result.addItems(res)
        self.flag_cb_contents_search_result = 1

    def contents_search_find_item(self, code):
        iterator = QtWidgets.QTreeWidgetItemIterator(self.treeWidget)
        while iterator.value():
            if iterator.value().text(0) == code:
                tree_item = iterator.value()
                break
            iterator.__iadd__(1)
        return tree_item

    def contents_search_goto(self):  # 如果是combobox 变化就激活这个槽函数
        code, contents = self.cb_contents_search_result.currentText().split("|")
        # for i in range(1, int(treecode.__len__() / 3) + 1):
        # print("i", i)
        # print("treecode[:i]", treecode[:i * 3])
        child = self.contents_search_find_item(code)
        # print("contents", contents)
        self.treeWidget.setCurrentItem(child)
        self.treeWidget.setFocus()
    # ---------------------------------------------------------------------

    def init_root(self):
        pass
        self.treeWidget.setColumnCount(3)
        self.treeWidget.setHeaderLabels(["编码", '行业名称', '生产性服务业'])
        self.treeWidget.setColumnWidth(0, 150)
        self.treeWidget.setColumnWidth(1, 300)
        self.treeWidget.setColumnWidth(2, 150)
        # 设置样式表以显示网格线
        self.treeWidget.setStyleSheet("""
                                        QTreeView::item
                                                        {
                                                            border-top:0px solid rgb(0,0,0);
                                                            border-left:0px solid rgb(0,0,0);
                                                            border-right:1px solid rgb(0,0,0);
                                                            border-bottom:1px solid rgb(0,0,0);
                                                        }
                                        QTreeView::item:selected:active { 
                                                            color:rgb(45,46,54);
                                                            background:rgb(186,204,217);
                                                        }
                                        """)
        self.treeWidget.setAlternatingRowColors(True)

        # --------------设置颜色-----------------
        self.brush = {
            "red": QtGui.QBrush(QtGui.QColor(255, 0, 0)),
            "black": QtGui.QBrush(QtGui.QColor(0, 0, 0))
        }
        # ---------------------------------------------------
        list_tag_content = []

        vs = self.tree_data["data"]
        # print("vs", vs)
        for i1 in range(vs.__len__()):
            # print("i1", i1)
            d1 = vs[i1]
            name, content = make_html_contents(d1["text"])
            list_tag_content.append([d1["tags"][0], name, content])
            child_1 = self.add_node(self.treeWidget, d1["tags"][0], name)
            self.DB.temp_in_db("", d1["tags"][0], name, "", content)
            # print(' d1["text"]', d1["text"])
            if d1["nodes"].__len__() > 0:
                for i2 in range(d1["nodes"].__len__()):
                    # print("i2", i2)
                    d2 = d1["nodes"][i2]
                    name, content = make_html_contents(d2["text"])
                    # print('d2["text"]', d2["text"])
                    list_tag_content.append([d2["tags"][0], name, content])
                    child_2 = self.add_node(child_1, d2["tags"][0], name)
                    self.DB.temp_in_db("", d2["tags"][0], name, "", content)

                    if d2["nodes"].__len__() > 0:
                        for i3 in range(d2["nodes"].__len__()):
                            # print("i3", i3)
                            d3 = d2["nodes"][i3]
                            name, content = make_html_contents(d3["text"])
                            list_tag_content.append([d3["tags"][0], name, content])
                            child_3 = self.add_node(child_2, d3["tags"][0], name)
                            self.DB.temp_in_db("", d3["tags"][0], name, "", content)

                            if d3["nodes"].__len__() > 0:
                                for i4 in range(d3["nodes"].__len__()):
                                    # print("i4", i4)
                                    d4 = d3["nodes"][i4]
                                    name, content = make_html_contents(d4["text"])
                                    list_tag_content.append([d4["tags"][0], name, content])
                                    child_4 = self.add_node(child_3, d4["tags"][0], name)
                                    self.DB.temp_in_db("", d4["tags"][0], name, "", content)

    def add_node(self, upper_item, tag, text):  # 注释内容未知, factory_code

        child = QtWidgets.QTreeWidgetItem(upper_item)
        child.setText(0, str(tag))
        child.setText(1, str(text))
        shengchan_code = self.DB.make_list(str(tag))
        if shengchan_code == [(None,)] or shengchan_code == []:
            child.setText(2, "")
        else:
            child.setText(2, shengchan_code[0][0])
            child.setForeground(0, self.brush["red"])
            child.setForeground(1, self.brush["red"])
            child.setForeground(2, self.brush["red"])
        return child

   # --------------------------------------------------------------
    def request_source(self, url, headers):

        response = requests.get(url, headers=headers)
        return response

    def search_it(self, content_text):
        # print("content_text", content_text)
        if content_text != "":
            url = "https://jcfx.tjj.zj.gov.cn:6443/autocode-clusterapi-pub/api/stats/query/mobile/des/{}/3".format(
                content_text)
            response = self.request_source(url, self.headers)
            # self.echo(url)
            # self.echo(response)
            # self.echo(response.text)
            if response == '400':
                return [], "Err", "Hints", "msg"
            try:
                data = json.loads(response.text)
            except:
                return [], "Err", "Hints", "msg"
            if data["code"] != "00000":
                return [], "Err", "Hints", "msg"

            result = []
            for r in data["data"]["Codes"]:
                result.append([r["Category"], r["Code"], r["Exact"], r["Weight"], r["Name"]])
            Err = data["data"]["Err"]
            Hints = data["data"]["Hints"]
            msg = data["msg"]
            return result, Err, Hints, msg
        else:
            return [], "Err", "Hints", "msg"

    def search_html(self, code, class_):
        self.txtb_now.setHtml("")  # 先把描述框清空
        # print("content_text", code, class_)
        if class_ != "":
            url = "https://jcfx.tjj.zj.gov.cn:6443/autocode-clusterapi-pub/api/stats/query/detail/{}/{}".format(
                code, class_)
            response = self.request_source(url, self.headers)
            # self.echo(url)
            # self.echo(response)
            # self.echo(response.text)
            if response == '400':
                return "错误"

            data = json.loads(response.text)
            if data["code"] != "00000":
                return "错误"

            html = data["data"]

            return html
        else:
            return "错误"


# -------------------------------------------------------------------------------------------------------------------


    def set_html(self, a, b):
        # print("a,b,html_text", a, b)
        code = self.tb_urls.item(a, 0).text()
        class_ = self.tb_urls.item(a, 2).text()
        html = self.search_html(code, class_)
        self.txtb_now.setHtml(html)

    def set_contents(self, content="*"):
        # print("a,b,html_text", a, b)
        self.txtb_whole.setHtml("")

        item = self.treeWidget.currentItem()
        content = self.le_contents_search.text()
        code = item.text(0)
        text = self.DB.make_contents(code)[0][0]

        self.txtb_whole.clear()
        if text:
            texts = text.split("****")

            for t in texts:
                x = ""
                if content in t:
                    x = t.replace(content, '<span style=\" font-size:16pt; font-weight:600; color:#ff0000;\">{}</span>'.format(content))
                else:
                    x = t.replace(content,
                                  '<span style=\" fon.t-size:16pt; font-weight:600; color:#ffffff;\">{}</span>'.format(
                                      content))
                # text
                self.txtb_whole.append(x)  # .replace(content, '<span style=\" font-weight:600; color:#ff0000;\">{}</span>'.format(content)
        self.txtb_whole.moveCursor(self.txtb_whole.textCursor().Start)  # 文本框显示到底部

    def Table_Init(self):
        cart_len_width = [100, 300, 300, 200, 300]  # tb_cart
        for i in range(cart_len_width.__len__()):
            self.tb_urls.setColumnWidth(i, cart_len_width[i])
        self.tb_urls.verticalHeader().setDefaultSectionSize(30)
        self.tb_urls.horizontalHeader().setStretchLastSection(True)

    def label_show(self, text, now, all_):
        if text == "clear":
            self.tB_log.clear()
            self.progressBar.setValue(0)
        elif text == "end":
            self.tB_log.clear()
            self.progressBar.setValue(100)
            self.stop_Update_Url()
        else:
            self.tB_log.append(text)
            self.progressBar.setValue(int((now * 100) / all_))
        with open("./log.txt", "a") as file:
            file.write(text)
            file.write("\n")

    def List_Clear(self):
        self.le_title.clear()
        # self.le_content.clear()
        self.List_Refresh()
        self.txtb_now.setHtml("")
        self.txtb_whole.setHtml("")
        self.le_code_search.clear()
        self.le_name_search.clear()
        self.le_contents_search.clear()
        self.txtb_hints.clear()

    def List_Refresh(self):  # 刷新购物车表内容
        title_words = self.le_title.text().replace(" ", "")
        # title_words = "齐一煤化工集团有限公司"

        result = self.search_it(title_words)  # , content_words
        self.echo(result)
        if result[0] == []:  # 返回空结果的时候
            self.table_fill(self.tb_urls, [])
            self.txtb_now.setHtml('无返回结果')
            self.txtb_hints.setHtml('无返回结果')
        else:
            filler_result = []
            for l in result[0]:
                shengchan_code = self.DB.make_list(l[1])[0]
                # print("shengchan_code", shengchan_code)
                if shengchan_code[0] != None:
                    filler_result.append([l[1], l[0], l[4], l[3], shengchan_code[0]])
                else:
                    filler_result.append([l[1], l[0], l[4], l[3], "------------------"])
            self.txtb_hints.append(str(result[1]))
            self.txtb_hints.append(str(result[2]))

            self.table_fill(self.tb_urls, filler_result)
        #

    def echo(self, *args):
        print(datetime.datetime.now())
        print([str(i) for i in args])

    def table_fill(self, object_wid, result):  # 通用 刷新搜索表格内容
        object_wid.setRowCount(0)
        object_wid.clearContents()
        rows = result.__len__()
        for i in range(rows):
            object_wid.removeRow(i)
        object_wid.setRowCount(rows)
        for i in range(rows):
            data = result[i]
            for j in range(data.__len__()):  # 116935471720116
                object_wid.setItem(i, j, QTableWidgetItem(str(data[j])))
            #     object_wid.item(i, j).setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        object_wid.clearSelection()

    def Show_Info(self, a):  # 双击显示具体信息
        idx = self.tb_urls.currentRow()
        url = self.tb_urls.item(idx, 2).text()
        self.thread_browser = threads.Browser()
        self.thread_browser.url = url
        self.showMaximized()
        self.thread_browser.start()

    def Exit(self):
        app.quit()

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key() == Qt.Key_Escape:
            self.tray.onIconClicked(3)
        # elif QKeyEvent.key() == Qt.Key_Return:
        #     self.List_Refresh()

    def minimized(self):
        self.tray.onIconClicked(2)

    def mousePressEvent(self, event):  # 重写鼠标点击事件
        if event.button() == QtCore.Qt.LeftButton:
            self.Move = True  # 鼠标按下时设置为移动状态
            self.Point = event.globalPos() - self.pos()  # 记录起始点坐标
            event.accept()

    # def mouseMoveEvent(self, QMouseEvent):  # 移动时间
    #     if self.isMaximized() == 0:
    #         if QtCore.Qt.LeftButton and self.Move == False:  # 切记这里的条件不能写死，只要判断move和鼠标执行即可！
    #             self.move(QMouseEvent.globalPos() - self.m_Position)  # 移动到鼠标到达的坐标点！
    #             QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):  # 结束事件
        self.Move = False


if __name__ == '__main__':
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    # qdarkstyle
    app.setStyleSheet(load_stylesheet(qt_api='pyqt5'))
    main_window = MED_SELL()
    main_window.show()
    # main_window.showMaximized()
    sys.exit(app.exec_())
